<template>
    <div class="trade-ops-wrap"
    :data-multi="multiSliderMax"
    :data-close="closeSliderMax"
    :data-open="openSliderMax">
        <div class="flex-hor-layout op-type-box">
            <div class="type pointer" :class='{"selected": selectedOpType === 0}' @click=switchType(0)>买入/做多</div>
            <div class="type pointer" :class='{"selected": selectedOpType === 1}' @click=switchType(1)>卖出/做空</div>
            <div class="type pointer" :class='{"selected": selectedOpType === 2}' @click=switchType(2)>对冲/多空</div>
        </div>

        <div class="ops-box">
            <div v-show="selectedOpType === 0" class="">
                <div class="row flex-hor-layout">
                    <div class="left">
                        <div class="border-box type">
                          <el-select v-model="openPosition.priceType"
                            class="black-select"
                            popper-class="black-dropdown"
                            placeholder="请选择">
                            <el-option
                              v-for="item in openPosition.priceTypeOptions"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value">
                              <span style="float: left">{{ item.label }}</span>
                            </el-option>
                          </el-select>
                        </div>
                    </div>
                    <div class="right" @click="showLeverageDialog">
                        <div class="border-box leverage pointer" contenteditable="false">
                          {{ openPosition._leverage }}X
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="title">开仓价<span class="float-right">USDT</span></div>
                    <div class="border-box">
                      <template v-if="openPosition.priceType === 0 || openPosition.priceType === 2">
                        <input class="borderless" disabled="true" type="text" placeholder="以最新的市场价格成交"></input>
                      </template>
                      <template v-else>
                        <input class="borderless" type="number" v-model="openPosition._price"></input>
                      </template>
                    </div>
                </div>
                <div class="row" :class="{'no-bottom-border': openPosition.priceType === 2 || openPosition.priceType === 3}">
                    <div class="title">开仓量<span class="float-right">{{getCurPaireObj.token}}</span></div>
                    <div class="border-box">
                      <input class="borderless" v-model="openPosition._size" type="number"></input>
                    </div>
                </div>
                <div class="row no-top-border">
                  <div class="border-box flex-hor-layout"
                    v-show="openPosition.priceType === 2 || openPosition.priceType === 3">
                    <input class="borderless" v-model="openPosition.upPrice" type="number" placeholder="止盈价格"></input>
                    <div class="unit">USDT</div>
                    <div class="ver-line"></div>
                    <input class="borderless" v-model="openPosition.downPrice" type="number" placeholder="止损价格"></input>
                    <div class="unit">USDT</div>
                  </div>
                  <div class="amount-tip-box flex-hor-layout" v-show="openPosition.priceType === 2 || openPosition.priceType === 3">
                    <div class="item">
                      * 预计盈利<span class="green">{{openUpAmount}}USDT</span>
                    </div>
                    <div class="item">
                      * 预计亏损<span class="red">{{openDownAmount}}USDT</span>
                    </div>
                  </div>
                </div>

                <div class="row slider-row">
                  <el-slider v-model="openSlider" class="yellow-slider"
                    :max="openPosition.max || max"
                     :show-input=true></el-slider>
                  <div class="percents-box flex-hor-layout">
                    <div class="">0%</div>
                    <div class="split"></div>
                    <div class="">25%</div>
                    <div class="split"></div>
                    <div class="">50%</div>
                    <div class="split"></div>
                    <div class="">75%</div>
                    <div class="split"></div>
                    <div class="">100%</div>
                  </div>
                  <div class="tips">&nbsp;</div>
                </div>
                <div class="btn-box">
                    <button class="btn buy-btn float-right" @click="handleOpen">买入/做多</button>
                </div>
            </div>
            <div v-show="selectedOpType === 1" class="">
                <div class="row flex-hor-layout">
                    <div class="left">
                        <div class="border-box">
                          <el-select v-model="closePosition.priceType"
                            class="black-select"
                            popper-class="black-dropdown"
                            placeholder="请选择">
                            <el-option
                              v-for="item in closePosition.priceTypeOptions"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value">
                              <span style="float: left">{{ item.label }}</span>
                            </el-option>
                          </el-select>
                        </div>
                    </div>
                    <div class="right" @click="showLeverageDialog">
                        <div class="border-box" contenteditable="false">
                          {{ closePosition._leverage }}X
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="title">开仓价<span class="float-right">USDT</span></div>
                    <div class="border-box">
                      <template v-if="closePosition.priceType === 0 || closePosition.priceType === 2">
                        <input class="borderless" disabled="true" type="text" placeholder="以最新的市场价格成交"></input>
                      </template>
                      <template v-else>
                        <input class="borderless" type="number" v-model="closePosition._price"></input>
                      </template>
                    </div>
                </div>
                <div class="row" :class="{'no-bottom-border': closePosition.priceType === 2 || closePosition.priceType === 3}">
                    <div class="title">开仓量<span class="float-right">{{getCurPaireObj.token}}</span></div>
                    <div class="border-box">
                      <input class="borderless" v-model="closePosition._size" type="number"></input>
                    </div>
                </div>
                <div class="row no-top-border">
                  <div class="border-box flex-hor-layout" v-show="closePosition.priceType === 2 || closePosition.priceType === 3">
                    <input class="borderless" v-model="closePosition.upPrice" type="number" placeholder="止盈价格"></input>
                    <div class="unit">USDT</div>
                    <div class="ver-line"></div>
                    <input class="borderless" v-model="closePosition.downPrice" type="number" placeholder="止损价格"></input>
                    <div class="unit">USDT</div>
                  </div>
                  <div class="amount-tip-box flex-hor-layout" v-show="closePosition.priceType === 2 || closePosition.priceType === 3">
                    <div class="item">
                      * 预计盈利<span class="green">{{closeUpAmount}}USDT</span>
                    </div>
                    <div class="item">
                      * 预计亏损<span class="red">{{closeDownAmount}}USDT</span>
                    </div>
                  </div>
                </div>
                <div class="row slider-row">
                  <el-slider v-model="closeSlider" class="yellow-slider"
                    :max="closePosition.max || max" :show-input=true></el-slider>
                  <div class="percents-box flex-hor-layout">
                    <div class="">0%</div>
                    <div class="split"></div>
                    <div class="">25%</div>
                    <div class="split"></div>
                    <div class="">50%</div>
                    <div class="split"></div>
                    <div class="">75%</div>
                    <div class="split"></div>
                    <div class="">100%</div>
                  </div>
                  <div class="tips">&nbsp;</div>
                </div>
                <div class="btn-box">
                    <button class="btn sell-btn float-right" @click="handleClose">卖出/做空</button>
                </div>
            </div>
            <div v-show="selectedOpType === 2" class="">
                <div class="row flex-hor-layout">
                    <div class="left">
                        <div class="border-box">
                          <el-select v-model="multiPosition.priceType"
                            class="black-select"
                            popper-class="black-dropdown"
                            placeholder="请选择">
                            <el-option
                              v-for="item in multiPosition.priceTypeOptions"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value">
                              <span style="float: left">{{ item.label }}</span>
                            </el-option>
                          </el-select>
                        </div>
                    </div>
                    <div class="right" @click="showLeverageDialog">
                        <div class="border-box" contenteditable="false">
                          {{ multiPosition._leverage }}X
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="title">开仓价<span class="float-right">USDT</span></div>
                    <div class="border-box">
                      <template v-if="multiPosition.priceType === 0 || multiPosition.priceType === 2">
                        <input class="borderless" disabled="true" type="text" placeholder="以最新的市场价格成交"></input>
                      </template>
                      <template v-else>
                        <input class="borderless" type="number" v-model="multiPosition._price"></input>
                      </template>
                    </div>
                </div>
                <div class="row">
                    <div class="title">开仓量<span class="float-right">{{getCurPaireObj.token}}</span></div>
                    <div class="border-box">
                      <input class="borderless" v-model="multiPosition._size" type="number"></input>
                    </div>
                </div>
                <div class="row no-top-border">
                </div>
                <div class="row slider-row">
                  <el-slider v-model="multiSlider" class="yellow-slider"
                    :max="multiPosition.max || max" :show-input=true></el-slider>
                  <div class="percents-box flex-hor-layout">
                    <div class="">0%</div>
                    <div class="split"></div>
                    <div class="">25%</div>
                    <div class="split"></div>
                    <div class="">50%</div>
                    <div class="split"></div>
                    <div class="">75%</div>
                    <div class="split"></div>
                    <div class="">100%</div>
                  </div>
                  <div class="tips">{{multiPosition.tips}}</div>
                </div>
                <div class="btn-box">
                    <button class="btn hedging-btn float-right" @click="handleMulti">对冲/多空</button>
                </div>
            </div>
        </div>


        <el-dialog
            title="杠杆设置"
            :visible.sync="showDialog"
            :lock-scroll="false"
            class="black-dialog medium-dialog leverage-dialog"
            width="30%">
            <div class="dialog-form">
                <div class="row flex-hor-layout">
                    <div class="item icon minus-icon border-box pointer" @click="handleMinus">
                    </div>
                    <div class="mid pos-rel border-box">
                      {{curPosition._leverage}}
                    </div>
                    <div class="item icon plus-icon border-box pointer" @click="handlePlus">
                    </div>
                </div>
                <div class="row slider-row pos-rel">
                  <div class="header pos-abs">杠杆<span class="float-right">10X</span></div>
                  <el-slider v-model="curPosition._leverage" class="yellow-slider"
                              :max="10"
                              :min="1"
                              :show-input=true
                              :format-tooltip="formatTooltip"></el-slider>
                </div>
                <div class="row account-row">
                </div>
                <div class="btn ok-btn pointer" @click="changeLeverage">确 定</div>
            </div>
        </el-dialog>
    </div>
</template>
<script>
    import { mapGetters } from 'vuex'
    import ToastUtils from '@/utils/toastUtils.js'
    import {transferAttr2Int, fck} from '@/filters'
    import {getMaxOpenSize} from '@/utils/web3Utils.js'
    import {debounce} from '@/utils/eventUtils.js'
    const keyArr = ['_size', '_leverage']
    const _precise = ['_price', 'upPrice', 'downPrice']

    export default {
        name: 'TradeOps',
        components: {
        },
        data() {
            return {
                max:0,
                showDialog: false,
                selectedOpType: 0,
                leverageOptions: [
                ],
                openPosition: {
                  priceTypeOptions: [
                    { label: '市价委托', value: 0 },
                    { label: '限价委托', value: 1 },
                    { label: '市价止盈止损', value: 2 },
                    { label: '限价止盈止损', value: 3 }
                  ],
                  priceType: 0,
                  _side: 0,
                  _price: 0,
                  _size: 0,
                  _leverage: 5,
                  // upPrice: 0,
                  // downPrice: 0,
                  max: 0
                },
                closePosition: {
                  priceTypeOptions: [
                    { label: '市价委托', value: 0 },
                    { label: '限价委托', value: 1 },
                    { label: '市价止盈止损', value: 2 },
                    { label: '限价止盈止损', value: 3 }
                  ],
                  priceType: 0,
                  _side: 0,
                  _price: 0,
                  _size: 0,
                  _leverage: 5,
                  // upPrice: 0,
                  // downPrice: 0,
                  max: 0
                },
                multiPosition:{
                  priceTypeOptions: [
                    { label: '市价委托', value: 0 }
                    // { label: '限价委托', value: 1 },
                    // { label: '市价止盈止损', value: 2 },
                    // { label: '限价止盈止损', value: 3 }
                  ],
                  priceType: 0,
                  _side: 0,
                  _price: 0,
                  _size: 0,
                  _leverage: 10,
                  // upPrice: 0,
                  // downPrice: 0,
                  tips: '*多空仓位各占一半',
                  max: 0
                },
                curPosition: {
                }
            }
        },
        computed: {
            ...mapGetters([
              'addr',
              'account',
              'board',
              'user'
            ]),
            openUpAmount(){
              let openPrice = this.user.spotPrice || fck(this.user.curPrice, 8, 0)
              let price = fck(this.openPosition.upPrice, 8, 0)
              let size = this.openSlider
              let rs = '--'
              if(price > openPrice) {
                rs = fck((price - openPrice) * size, -8, 2)
              }
              return rs
            },
            openDownAmount(){
              let openPrice = this.user.spotPrice || fck(this.user.curPrice, 8, 0)
              let price = fck(this.openPosition.downPrice, 8, 0)
              let size = this.openSlider
              let rs = '--'
              if(price < openPrice) {
                rs = fck((openPrice - price ) * size, -8, 2)
              }
              return rs
            },
            closeUpAmount(){
              let openPrice = this.user.spotPrice || fck(this.user.curPrice, 8, 0)
              let price = fck(this.closePosition.upPrice, 8, 0)
              let size = this.closeSlider
              let rs = '--'
              if(price > openPrice) {
                rs = fck((price - openPrice) * size, -8, 2)
              }
              return rs
            },
            closeDownAmount(){
              let openPrice = this.user.spotPrice || fck(this.user.curPrice, 8, 0)
              let price = fck(this.closePosition.downPrice, 8, 0)
              let size = this.closeSlider
              let rs = '--'
              if(price < openPrice) {
                rs = fck((openPrice - price ) * size, -8, 2)
              }
              return rs
            },
            openSlider:{
              get(){
                return parseInt(this.openPosition._size)
              },
              set(newVal){
                this.openPosition._size = newVal
              }
            },
            closeSlider:{
              get(){
                return parseInt(this.closePosition._size)
              },
              set(newVal){
                this.closePosition._size = newVal
              }
            },
            multiSlider:{
              get(){
                return parseInt(this.multiPosition._size)
              },
              set(newVal){
                this.multiPosition._size = newVal
              }
            },
            openSliderMax(){
              this.openSliderMaxMethod()
            },
            closeSliderMax(){
              this.closeSliderMaxMethod()
            },
            multiSliderMax(){
              this.multiSliderMaxMethod()
            },
        },
        watch: {
          'user.curPaireObj': function(newVal) {
            this.openSliderMaxMethod()
          }
        },
        created() {
          for (let i = 1; i <= 10; i++) {
            this.leverageOptions.push({
              label: `${i} X`,
              value: i
            })
          }
          this.curPosition = this.openPosition
        },
        methods: {
          switchType(type) {
              this.selectedOpType = type
              switch(type){
                case 0:
                  this.openSliderMaxMethod()
                  break
                case 1:
                  this.closeSliderMaxMethod()
                  break
                case 2:
                  this.multiSliderMaxMethod()
                  break
              }
          },
          openSliderMaxMethod(){
            let price = this.openPosition.priceType === 0 || this.openPosition.priceType === 2 ?
            this.user.spotPrice : parseInt(fck(this.openPosition._price, 8, 0))
            const {_leverage} = this.openPosition
            log('tradeOps.vue/watch/openSliderMax', {price, _leverage})
            debounce(this.getSliderMax.bind(this, ['open', 0, price, _leverage]))
          },
          closeSliderMaxMethod(){
            let price = this.closePosition.priceType === 0 || this.closePosition.priceType === 2 ?
            this.user.spotPrice : parseInt(fck(this.closePosition._price, 8, 0))
            const {_leverage} = this.closePosition
            log('tradeOps.vue/watch/closeSliderMax', {price, _leverage})
            debounce(this.getSliderMax.bind(this, ['close', 0, price, _leverage]))
          },
          multiSliderMaxMethod(){
            let price = this.multiPosition.priceType === 0 || this.multiPosition.priceType === 2 ?
            this.user.spotPrice : parseInt(fck(this.multiPosition._price, 8, 0))
            const {_leverage} = this.multiPosition
            log('tradeOps.vue/watch/multiSliderMax', {price, _leverage})
            debounce(this.getSliderMax.bind(this, ['multi', 0, price, _leverage]))
          },
          getSliderMax(slider){
            log('tradeOps.vue/getSliderMax', {slider})
            let type = slider[0]
            let side = slider[1]
            let price = slider[2]
            let leverage = slider[3]
            if(this.addr) {
              getMaxOpenSize(this.addr, side, price, leverage)
                .then(res => {
                  log('tradeOps.vue/getSliderMax', {type, res})
                  let newMax = parseInt(res)
                  switch(type){
                    case 'open':
                      if(newMax < this.openPosition.openSlider) {
                        this.openPosition.openSlider = newMax
                      }
                      this.openPosition.max = newMax
                      break
                    case 'close':
                    if(newMax < this.closePosition.closeSlider) {
                        this.closePosition.closeSlider = newMax
                      }
                      this.closePosition.max = newMax
                      break
                    case 'multi':
                    if(newMax < this.multiPosition.multiSlider) {
                        this.multiPosition.multiSlider = newMax
                      }
                      this.multiPosition.max = newMax
                      break
                  }
                })
                .catch(err => {

                })
            }
          },
          showLeverageDialog(){
            this.showDialog = true
            switch(this.selectedOpType){
              case 0:
                this.curPosition = this.openPosition
                break
              case 1:
                this.curPosition = this.closePosition
                break
              default:
                this.curPosition = this.multiPosition
                break
            }
            console.log('tradeOps.vue==>>showLeverageDialog, curPosition: %o', this.curPosition)
          },
          changeLeverage(){
            this.showDialog = false
            switch(this.selectedOpType){
              case 0:
                this.openPosition._leverage = this.curPosition._leverage
                break
              case 1:
                this.closePosition._leverage = this.curPosition._leverage
                break
              default:
                this.multiPosition._leverage = this.curPosition._leverage
                break
            }
          },
          formatTooltip(val){
            return val + 'X'
          },
          handleMinus(){
            let {_leverage} = this.curPosition
            if(parseInt(_leverage) > 1){
              this.curPosition._leverage = parseInt(_leverage) - 1
            }
          },
          handlePlus(){
            let {_leverage} = this.curPosition
            if(parseInt(_leverage) < 10){
              this.curPosition._leverage = parseInt(_leverage) + 1
            }
          },
          handleOpen(){
            console.log('tradeOps.vue==>>handleOpen, openPosition: %o, filter', this.openPosition, this)
            const {priceType, _price, _size, _leverage, upPrice, downPrice} = transferAttr2Int(this.openPosition, keyArr, _precise)
            if(this.checkForm(priceType, _price, _size)){
              //
              console.log('tradeOps.vue==>>handleOpen, openPosition')
              switch(priceType){
                case 0:
                case 1:
                  openPosition(0, _size, _price, _leverage)
                    .then(res=>{
                      console.log('tradeOps.vue==>>handleOpen, res: %o', res)
                      var id = setInterval(()=>{
                        getInfoByTransaction(res, (err, data) => {
                          console.log('tradeOps.vue==>>handleOpen.getInfoByTransaction err: %o, data: %o', err, data)
                          if(!err){
                            if(data.block) {
                              this.$store.dispatch('user/updateAccount', this.addr)
                              ToastUtils.showMsg('做多操作上链成功')
                              clearInterval(id)
                            }
                          }else{
                            ToastUtils.showMsg('做多操作失败')
                          }
                        })
                      }, 2000)
                    })
                    .catch(err=>{
                      ToastUtils.showMsg('做多操作失败')
                    })
                  break
                default:
                  if(upPrice){
                    closePosition(0, _size, upPrice, _leverage)
                      .then(res=>{
                        console.log('tradeOps.vue==>>handleOpen, res: %o', res)
                      })
                      .catch(err=>{
                        // ToastUtils.showMsg('做多操作失败')
                      })
                  }
                  if(downPrice){
                    closePosition(0, _size, downPrice, _leverage)
                      .then(res=>{
                        console.log('tradeOps.vue==>>handleOpen, res: %o', res)
                      })
                      .catch(err=>{
                        // ToastUtils.showMsg('做多操作失败')
                      })
                  }
                  break
              }

            }
          },
          handleClose(){
            console.log('tradeOps.vue==>>handleClose, closePosition: %o', this.closePosition)
            const {priceType, _price, _size, _leverage, upPrice, downPrice} = transferAttr2Int(this.closePosition, keyArr, _precise)
            if(this.checkForm(priceType, _price, _size)){
              //
              console.log('tradeOps.vue==>>handleClose, closePosition')
              switch(priceType){
                case 0:
                case 1:
                  openPosition(1, _size, _price, _leverage)
                    .then(res=>{
                      console.log('tradeOps.vue==>>handleClose, res: %o', res)
                      var id = setInterval(()=>{
                        getInfoByTransaction(res, (err, data) => {
                          console.log('tradeOps.vue==>>handleClose.getInfoByTransaction err: %o, data: %o', err, data)
                          if(!err){
                            if(data.block) {
                              this.$store.dispatch('user/updateAccount', this.addr)
                              ToastUtils.showMsg('做空操作上链成功')
                              clearInterval(id)
                            }
                          }else{
                            ToastUtils.showMsg('做空操作失败')
                          }
                        })
                      }, 2000)
                    })
                    .catch(err=>{
                      ToastUtils.showMsg('做空操作失败')
                    })
                  break
                default:
                  if(upPrice){
                      closePosition(1, _size, upPrice, _leverage)
                        .then(res=>{
                          console.log('tradeOps.vue==>>handleOpen, res: %o', res)
                        })
                        .catch(err=>{
                          // ToastUtils.showMsg('做多操作失败')
                        })
                    }
                    if(downPrice){
                      closePosition(1, _size, downPrice, _leverage)
                        .then(res=>{
                          console.log('tradeOps.vue==>>handleOpen, res: %o', res)
                        })
                        .catch(err=>{
                          // ToastUtils.showMsg('做多操作失败')
                        })
                    }
                  break
              }
            }
          },
          handleMulti(){
            console.log('tradeOps.vue==>>handleMulti, multiPosition: %o', this.multiPosition)
            const {priceType, _price, _size} = transferAttr2Int(this.multiPosition, keyArr, _precise)
            if(this.checkForm(priceType, _price, _size)){
              //
              console.log('tradeOps.vue==>>handleMulti, multiPosition')
              let long = _size * this.multiPosition.slider / 100
              let short = _size * (100 - this.multiPosition.slider) / 100
              if(long){
                openPosition(0, long, _price, _leverage)
                  .then(res=>{
                    console.log('tradeOps.vue==>>handleMulti, res: %o', res)
                  })
                  .catch(err=>{
                    ToastUtils.showMsg('对冲操作失败')
                  })
              }

              if(short){
                openPosition(1, short, _price, _leverage)
                  .then(res=>{
                    console.log('tradeOps.vue==>>handleMulti, res: %o', res)
                  })
                  .catch(err=>{
                    ToastUtils.showMsg('对冲操作失败')
                  })
              }
            }
          },
          checkForm(priceType, _price, _size) {
            switch(priceType) {
              case 0:
              case 2:
                if(!parseFloat(_size)) {
                  ToastUtils.showMsg('请填写开仓量')
                  return
                }
                break
              case 1:
              case 3:
                if(!parseFloat(_price)){
                  ToastUtils.showMsg('请填写开仓价')
                  return
                }
                if(!parseFloat(_size)) {
                  ToastUtils.showMsg('请填写开仓量')
                  return
                }
                break
              default:
                break
            }
            return true
          }
        },

    }
</script>
<style lang="scss" scoped>
    @import "./index.scss";
</style>
